/**
 * Created by yangbajing(yangbajing@gmail.com) on 2016-08-22.
 */
import axios from "axios";
import {browserHistory} from "react-router";
import {notification} from 'antd';

axios.defaults.headers.common['Demo-APP-KEY'] = 'demo';
// axios.defaults.headers.common['If-Modified-Since'] = '0';

axios.interceptors.request.use(
    config => config,
    error => Promise.reject(error));

export function makeActionCreator(type, ...argNames) {
    return function (...args) {
        let action = {type};
        argNames.forEach((arg, index) => {
            action[argNames[index]] = args[index]
        });
        return action
    }
}

export function request(config) {
    return axios(config)
        .then(resp => {
            const data = resp.data;
            if (data.errCode && data.errCode !== 0) {
                if (data.errCode == 401) {
                    console.error(data);
                    // browserHistory.push('/site/login.html');
                    return;
                }
                let error = new Error();
                error.errCode = data.errCode;
                error.errMsg = data.errMsg;
                error.data = data.data;
                return Promise.reject(error);
            }
            return Promise.resolve(resp.data);
        })
        .catch(error => {
            if (error.response) {
                if (error.response.status == 401) {
                    console.warn(error);
                    // window.location.href = '/site/login.html';
                    // return;
                }

                const data = error.response.data || {
                        errCode: error.response.status,
                        errMsg: error.response.statusText
                    };
                error.errCode = data.errCode || data.status;
                error.errMsg = data.errMsg || data.error;
            } else {
                if (!error.errCode) {
                    error.errCode = -1;
                    error.errMsg = error.toString();
                }
            }
            return Promise.reject(error);
        })
}

/**
 * success和error参数选荐见：https://ant.design/components/notification/。
 * 需要注意的是success.type和error.type用于了redux action type，若要设置Notification config.type请使用notificationType属性设置。
 * success与error参数未指定message属性则不显示全局通知消息
 *
 * @param dispatch redux action dispatch
 * @param config axios config
 * @param success {type, title, description, notificationType: 默认为'success')
 * @param error {type, title, description, notificationType: 默认为'error') [可选]
 */
export function requestJSON(dispatch, config, success, error) {
    return request(config)
        .then(data => {
            if (success.message) {
                dispatch({
                    type: 'NOTIFICATION',
                    data: {...success, type: success.notificationType || 'success'}
                });
                notification.success({message: success.message})
            }

            dispatch({type: success.type, data});
            return Promise.resolve(data);
        })
        .catch(e => {
            if (error && error.message) {
                let data = {...error, type: error.notificationType || 'warn'};
                if (!data.description) {
                    data.description = e.errMsg || e.toString();
                }
                dispatch({
                    type: 'NOTIFICATION',
                    data,
                });
                notification.error({message: error.message})
            }

            dispatch({type: error.type, data: e});
            return Promise.reject(e);
        });
}

export function actionPromise(promise, dispatch, actionSuccessCreator, actionErrorCreator) {
    return promise
        .then(resp => {
            const data = resp.data;
            // console.log('actionPromise then: ', data);
            if (data.errCode && data.errCode !== 0) {
                dispatch(actionErrorCreator(data))
            } else {
                dispatch(actionSuccessCreator(data))
            }
        })
        .catch(error => {
            let data = null;
            console.info('axio error', error);
            if (!error.response) {
                data = {errCode: -1, errMsg: error.toString()};
            } else {
                const resp = error.response;
                data = resp.data || {errCode: resp.status, errMsg: resp.statusText};
            }
            dispatch(actionErrorCreator(data))
        })
}
